/*
 * MIT License
 *
 * Copyright (c) 2021 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.seaboot.excel.call2;

import cn.seaboot.excel.ExcelBook;
import cn.seaboot.excel.ExcelCell;
import cn.seaboot.excel.call.RowReaderAndWriter;
import com.google.common.annotations.Beta;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.jetbrains.annotations.NotNull;

/**
 * 字符串数组的读取
 * <p>
 * 优化了公式的内容读取，读取更加可靠，但是更加消耗性能。
 * <p>
 * 使用 {@link FormulaEvaluator} 读取单元格公式，结果更加可靠，但是读取稍慢；
 * 可能会考虑删除这一 API
 *
 * @author Mr.css
 * @version 2021-01-20 16:37
 */
@Beta
public class StringArrayReaderAndWriter implements RowReaderAndWriter<String[]> {

    /**
     * 指定数组长度
     * <p>
     * 默认情况下，Excel 中有多少列，就会读取到多长的数组，
     * <p>
     * 因为不确定数组多长，会对编程造成困难；
     * <p>
     * 如果指定了数组长度，数据读取的时候，会将结果集封装成定长数组，不足部分用 null 补充。
     */
    private Integer length;

    /**
     * 计算公式的时候会用到
     */
    private FormulaEvaluator evaluator;

    public StringArrayReaderAndWriter(Integer length) {
        this.length = length;
    }

    public StringArrayReaderAndWriter() {
    }

    @Override
    public void startup(Workbook book) {
        this.evaluator = book.getCreationHelper().createFormulaEvaluator();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String[] readRow(@NotNull Row row) {
        int len = length == null ? row.getLastCellNum() : length;
        String[] arr = new String[len];
        for (int j = 0; j < len; j++) {
            arr[j] = ExcelCell.readString2(evaluator, row.getCell(j));
        }
        return arr;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void writeRow(Row row, String[] array) {
        for (int i = 0; i < array.length; i++) {
            ExcelCell.addCell(row, i, array[i]);
        }
    }
}
